package domain

import (
	"fmt"
	"github.com/labstack/gommon/log"
	"gopkg.in/h2non/gentleman.v2"
	"os"
)

type CacheService struct {
	httpclient *gentleman.Client
	stateUrl   string
}

func NewCacheService() *CacheService {
	port, exist := os.LookupEnv("DAPR_HTTP_PORT")
	if !exist {
		port = "3500"
	}
	stateStoreName := `statestore`
	host := fmt.Sprintf(`http://localhost:%s`, port)
	stateUrl := fmt.Sprintf(`/v1.0/state/%s`, stateStoreName)

	cache := &CacheService{}
	cache.httpclient = gentleman.New()
	cache.httpclient.BaseURL(host)
	cache.stateUrl = stateUrl
	return cache
}

func (cache *CacheService) Add(data *Data) error {

	request := cache.httpclient.Post()
	request.Path(cache.stateUrl)
	state := &State{
		Key:   "order",
		Value: data,
	}
	states := []*State{state}
	response, err := request.JSON(&states).Send()
	if err != nil {
		return err
	}
	if !response.Ok {
		return fmt.Errorf("add state error,statuCode:%d,messag:%s", response.StatusCode, response.String())
	}

	log.Info("Successfully persisted state.")

	return nil
}

func (cache *CacheService) Query() (*Data, error) {

	request := cache.httpclient.Get()

	request.Path(cache.stateUrl + "/order")

	response, err := request.Send()

	if err != nil {
		return nil, err
	}
	if !response.Ok {
		return nil, fmt.Errorf("query state error,statuCode:%d,messag:%s", response.StatusCode, response.String())
	}

	data := &Data{}
	err = response.JSON(&data)

	return data, err

}

func (cache *CacheService) delete(id string) error {
	request := cache.httpclient.Delete()
	request.Path(cache.stateUrl + "/" + id)
	request.AddHeader("Content-Type", "application/json")
	response, err := request.Send()
	if err != nil {
		return err
	}
	if !response.Ok {
		return fmt.Errorf("delete state error,id:%s,statuCode:%d,messag:%s", id, response.StatusCode, response.String())
	}
	return nil
}
